<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Brands;
use app\admin\model\Category;
use app\admin\model\Goods;
use app\BaseController;
use app\common\traits\Jump;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\View;
use think\facade\Request;
use think\facade\Cache;
use think\exception\ValidateException;

class Good extends BaseController
{
    public function cate()
    {
        $parentid=Request::get('id',0);

        $cate = Category::getCategory($parentid);

        //方案一：按照父辈ID进行判断
        $cateal = Category::getCategoryl($parentid);
        View::assign('cateal',$cateal);

        View::assign('cate',$cate);

        if(Request::isPost()){
            $post = Request::post();
            $time = time();
            $post['addtime']=$time;
            list($res,$msg) = Category::CateAdd($post);
            if($res){
                $this->success($msg,url('Good/cate'));
            }else{
                $this->error($msg);
            }
        }else{
            return view();
        }
    }

    public function cateedit()
    {
        $id = Request::get('id');
        if(Request::isPost()){
            $post = Request::post();
            $time = time();
            $post['addtime']=$time;
            $jump = $post['jump'];
            unset($post['jump']);

            list($res,$msg) = Category::CateEdit($post,$id);

            if($res){
                if ($jump == 1){
                    $this->success($msg,url('Good/cate',input('get.')));
                }else{
                    $this->success($msg,url('Good/cateedit',input('get.')));
                }
            }else{
                $this->error($msg);
            }
        }else{//分类
            $cate = Category::Catego();
            View::assign('cate',$cate);
            $id = Request::get('id');
            $edit = Category::editCate($id);
            View::assign('edit',$edit);
            return view();
        }
    }

    public function goodAdd()
    {

        //使用缓存
        if(Cache::has('cate')){ //判断缓存变量是否存在
            $cateAll = Cache::get('cate');  //获取缓存数据
        }else{
            $cateAll = Db::table('ecm_category')->select()->toArray();
            Cache::set('cate',$cateAll,100); //设置缓存变量
        }
        //分类循环
        $cate = $this->getCate($cateAll,0);
        View::assign('cate',$cate);
        if(Request::isPost()){
            $post = Request::param();

        //try{
        //    $files = Request::file('banner');
        //}catch (\Exception $e){
        //    return [false,'没上传图片1'];
        //}
        //
        //if(!$files) return [false,'没上传图片2'];
        ////判断单图多图
        //if(is_array($files)){
        //    //多图上传
        //    $path = [];
        //    foreach ($files as $file){
        //        $img = Filesystem::putFile( 'img', $file,'md5'.time());
        //        $path[] = str_replace('\\','/',$img);
        //    }
        //    $path = implode(',',$path);
        //}
        //
        //try{
        //    $file = Request::file('img');
        //    try{
        //        validate(['image'=>'fileSize:102400|fileExt:jpg,png,jpeg,gif'])->check(['image'=>$file]);
        //    }catch (ValidateException $e){
        //        return "<script>alert('后缀名不对');history.back();</script>";
        //    }
        //    $patho = Filesystem::putFile('img',$file,'md5'.time());
        //    $patho = str_replace('\\','/',$patho);
        //
        //}catch (\Exception $e){
        //    return "<script>alert('请上传图片');history.back();</script>";
        //}
        //
        //$post['photo_x']=$patho;
        //$post['photo_string']=$path;
            list($res,$path) = Upload::upload('img');
            if($res) $post['photo_x']=$path;

            list($res1,$path1) = Upload::upload('banner');
            if ($res1) $post['photo_string'] = $path1;

            $time = time();
            $post['addtime']=$time;

            //$res = Goods::create($arr);
            list($res,$msg) = Goods::addInfo($post);

            if ($res){
                //$lin = app()->getRootPath().'public/static/admin/linshi/'.$path;
                //$zheng = app()->getRootPath().'public/static/admin/'.$path;
                //$dir = app()->getRootPath().'public/static/admin/img/20211027';
                //if (!is_dir($dir)){
                //    mkdir($dir,0777,true);
                //}
                //rename($lin,$zheng);
                Upload::removeImg($path);
            }
            if (isset($post['photo_string'])){
                //foreach ($post['imgs'] as $v){
                //
                //    $lin = app()->getRootPath().'public/static/admin/linshi/'.$v;
                //    $zheng = app()->getRootPath().'public/static/admin/'.$v;
                //    $dir = app()->getRootPath().'public/static/admin/img/'.date('Ymd',time());
                //    if (!is_dir($dir)){
                //        mkdir($dir,0777,true);
                //    }
                //    rename($lin,$zheng);
                //}
                $post['photo_string'] = explode(',',$post['photo_string']);
                Upload::removeImg($post['photo_string']);
            }

            if($res){
                $this->success($msg,url('Good/goodList'));
            }else{
                $this->error($msg);
            }
        }else{
            return view();
        }
    }

    public function goodList()
    {
        $input = input();

        $where=[];
        //关键字查询
        if (isset($input['keywords']) && !empty($input['keywords']))    $where['keywords'] = $input['keywords'];
        //是否推荐查询
        if(isset($input['is_show']) && $input['is_show']<>'')           $where['is_show'] = $input['is_show'];
        //是否热门查询
        if(isset($input['is_hot']) && $input['is_hot']<>'')             $where['is_hot'] = $input['is_hot'];
        //是否下架查询
        if(isset($input['is_down']) && count($input['is_down'])<2)      $where['is_down'] = $input['is_down'];
        //时间区间查询
        if (isset($input['addtime']) && $input['addtime']<>'')          $where['addtime']=$input['addtime'];
        if (isset($input['addtimes']) && $input['addtimes']<>'')        $where['addtimes']=$input['addtimes'];
        //价格区间查询
        if (isset($input['min']) && $input['min']<>'')        $where['min'] = $input['min'];
        if (isset($input['max']) && $input['max']<>'')        $where['max'] = $input['max'];
        //分类查询
        if (isset($input['cid']) && !empty($input['cid']))      $where['cid']=$input['cid'];

        $list = \app\admin\model\Goods::getGoods($where,$input);
        View::assign('list',$list);
        View::assign($input);

        //使用缓存
        if(Cache::has('cate')){ //判断缓存变量是否存在
            $cateAll = Cache::get('cate');  //获取缓存数据
        }else{
            $cateAll = Db::table('ecm_category')->select()->toArray();
            Cache::set('cate',$cateAll,100); //设置缓存变量
        }
        //2.1
        //$cate = [];
        ////循环所有分类  $v为每条分类
        //foreach ($cateAll as $v){
        //    //判断 分类中parentid字段等于0 进入判断结果 都是一级分类
        //    if($v['parentid'] == 0){
        //        //将$v一级分类赋值到空数组中  索引为自己的ID
        //        $cate[$v['id']] = $v;
        //        //循环所有分类
        //        foreach ($cateAll as $vv){
        //            //如果分类的parentid等于上一级分类(一级分类)ID 进入判断里的是二级分类
        //            if($vv['parentid'] == $v['id']){
        //                //将二级分类赋值到数组  根据索引($v.id) 将一级和二级绑定到一起
        //                $cate[$v['id']]['son'][$vv['id']] = $vv;
        //                //.......无限分类循环
        //            }
        //        }
        //    }
        //}

        //2.2
        $cate = $this->getCate($cateAll,0);
        View::assign('cate',$cate);

        return view();
    }

    public function getCate($cateAll,$parentid)
    {
        $cate = [];
        foreach ($cateAll as $v){
            if($v['parentid'] == $parentid){
                $cate[$v['id']] = $v;
                $cate[$v['id']]['son'] = $this->getCate($cateAll,$v['id']);
            }
        }
        return $cate;
    }

    public function goodEdit()
    {
        if(Request::isPost()){
            $id = Request::get('id');
            $post = Request::post();


            list($res,$path) = Upload::upload('img');
            if($res) $post['photo_x']=$path;


            list($res1,$path1) = Upload::upload('banner',false);
            if($res1 && isset($post['old_img'])){
                $post['photo_string'] = implode(',',array_merge($path1,$post['old_img']));
            }elseif (!$res1 && isset($post['old_img'])){
                $post['photo_string'] = implode(',',$post['old_img']);
            }elseif ($res1 && !isset($post['old_img'])){
                $post['photo_string'] = implode(',',$path1);
            }else{
                $post['photo_string'] = '';
            }

            //if($_FILES['img']['error']==0){
            //    $file = Request::file('img');
            //    try{
            //        validate(['image'=>'fileSize:1024000000|fileExt:jpg,png,jpeg,gif'])->check(['image'=>$file]);
            //    }catch (ValidateException $e){
            //        return "<script>alert('后缀名不对');history.back();</script>";
            //    }
            //    $path = Filesystem::putFile('img',$file,'md5'.time());
            //    $path = str_replace('\\','/',$path);
            //    $post['brand_logo']=$path;
            //}else{
            //    $path = $post['old'];
            //}

            $is_show=Request::post('is_show',0);
            $is_hot=Request::post('is_hot',0);
            $is_down=Request::post('is_down',0);

            $post['photo_x']=$path;
            $post['updatetime']=time();
            $post['is_hot']=$is_hot;
            $post['is_show']=$is_show;
            $post['is_down']=$is_down;

            $good = Db::name('goods')->where('id',$post['id'])->find();

            list($res2,$msg) = Goods::editInfo($post);

            if($res2){
                if ($res){
                    //$lin = app()->getRootPath().'public/static/admin/linshi/'.$path;
                    //$zheng = app()->getRootPath().'public/static/admin/'.$path;
                    //$dir = app()->getRootPath().'public/static/admin/img/20211027';
                    //if (!is_dir($dir)){
                    //    mkdir($dir,0777,true);
                    //}
                    //rename($lin,$zheng);
                    Upload::removeImg($path);
                }
                if ($res1){
                    //foreach ($post['imgs'] as $v){
                    //
                    //    $lin = app()->getRootPath().'public/static/admin/linshi/'.$v;
                    //    $zheng = app()->getRootPath().'public/static/admin/'.$v;
                    //    $dir = app()->getRootPath().'public/static/admin/img/'.date('Ymd',time());
                    //    if (!is_dir($dir)){
                    //        mkdir($dir,0777,true);
                    //    }
                    //    rename($lin,$zheng);
                    //}
                    $post['photo_string'] = explode(',',$post['photo_string']);
                    Upload::removeImg($post['photo_string']);
                }

                //删除老图
                $res3 = file_exists(app()->getRootPath().'public/static/admin/'.$good['photo_x']);
                if ($res && $res3 && $good['photo_x']) unlink(app()->getRootPath().'public/static/admin/'.$good['photo_x']);
                //删除多图中老图//$good['photo_string']   $post['old_img']
                if (isset($post['old_img']) && $good['photo_string']){
                    $old = explode(',',$good['photo_string']);
                    $unlink = array_diff($old,$post['old_img']);
                }elseif(!isset($post['old_img']) && $good['photo_string']){
                    $unlink = explode(',',$good['photo_string']);
                }
                if (isset($unlink) && !empty($unlink)){
                    foreach ($unlink as $v){
                        $res4 = file_exists(app()->getRootPath().'public/static/admin/'.$v);
                        if ($res4) unlink(app()->getRootPath().'public/static/admin/'.$v);
                    }
                }
                if ($post['jump'] == 1){
                    $this->success($msg,url('Good/goodList',input('get.')));
                }else{
                    $this->success($msg,url('Good/goodEdit',input('get.')));
                }
            }else{
                $this->error($msg);
            }
        }else{
            //使用缓存
            if(Cache::has('cate')){ //判断缓存变量是否存在
                $cateAll = Cache::get('cate');  //获取缓存数据
            }else{
                $cateAll = Db::table('ecm_category')->select()->toArray();
                Cache::set('cate',$cateAll,100); //设置缓存变量
            }
            $cate = $this->getCate($cateAll,0);
            View::assign('cate',$cate);

            $id = Request::get('id');
            $edit = Goods::getInfo($id);
            $edit = $edit->toArray();
            $edit['photo_string'] = $edit['photo_string']?explode(',',$edit['photo_string']):'';

            View::assign('',$edit);

            return view('',$edit);
        }

    }

    public function ajax()
    {
        if(Request::isPost()){
            $post = Request::post();
            $good = Goods::destroy($post);
            if($good>0){
                echo '成功';
                exit;
            }else{
                echo '失败';
                exit;
            }
        }
    }

    public function del()
    {
        $input = input('id');
        $good = Goods::destroy([$input]);
        if($good>0){
            echo "<script>alert('删除成功');history.back();</script>";
            exit;
        }else{
            echo '失败';
            exit;
        }
    }

}










